package com.selectlight;

/**
 * opencv 检测图片亮度
 * brightnessException 计算并返回一幅图像的色偏度以及，色偏方向
 * cast 计算出的偏差值，小于1表示比较正常，大于1表示存在亮度异常；当cast异常时，da大于0表示过亮，da小于0表示过暗
 * 返回值通过cast、da两个引用返回，无显式返回值
 */

import com.controllight.BrightnessManager;
import org.opencv.core.Mat;
import org.opencv.imgproc.Imgproc;

import java.io.IOException;

public class BrightnessExceptions {
    public static Integer brightnessException(Mat jpegFile) throws IOException {
        Mat srcImage = jpegFile;
        Mat dstImage = new Mat();
        // 将RGB图转为灰度图
        Imgproc.cvtColor(srcImage, dstImage, Imgproc.COLOR_BGR2GRAY);
        float a = 0;
        int Hist[] = new int[256];
        for (int i = 0; i < 256; i++) {
            Hist[i] = 0;
        }
        for (int i = 0; i < dstImage.rows(); i++) {
            for (int j = 0; j < dstImage.cols(); j++) {
                //在计算过程中，考虑128为亮度均值点
                a += (float) (dstImage.get(i, j)[0] - 128);
                int x = (int) dstImage.get(i, j)[0];
                Hist[x]++;
            }
        }
        float da = a / (float) (dstImage.rows() * dstImage.cols());
        System.out.println(da);
        if (da > 0) {
            BrightnessManager.setBrightness((int) da * 7 / 11);
        } else {
            BrightnessManager.setBrightness(0);
        }
        float D = Math.abs(da);
        float Ma = 0;
        for (int i = 0; i < 256; i++) {
            Ma += Math.abs(i - 128 - da) * Hist[i];
        }
        Ma /= (float) ((dstImage.rows() * dstImage.cols()));
        float M = Math.abs(Ma);
        float K = D / M;
        float cast = K;
        System.out.printf("亮度指数： %f\n", cast);
        if (cast >= 1) {
            System.out.printf("亮度：" + da);
            if (da > 0) {
                System.out.printf("过亮\n");
                return 2;
            } else {
                System.out.printf("过暗\n");
                return 1;
            }
        } else {
            System.out.printf("亮度：正常\n");
            return 0;
        }
    }
}
